from django.db import transaction
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.hashers import make_password

from users.models import CustomUser
from users.serializers import UserSerializer


class CustomUserListView(APIView):
    # 权限为管理员
    permission_classes = [IsAdminUser]

    def get(self, request):
        """
        获取所有用户
        :param request:
        :return: 返回所有用户
        """
        queryset = CustomUser.objects.all()
        serializer = UserSerializer(instance=queryset, many=True)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)


class CustomUserDetailView(APIView):
    # permission_classes = [IsAuthenticated]  # 权限为登录用户

    def get(self, request, pk):
        """
        获取用户详情
        :param request:
        :param pk:
        :return: 返回用户详情
        """
        try:
            queryset = CustomUser.objects.get(pk=pk)
        except CustomUser.DoesNotExist as e:
            return Response({'error': "用户不存在"}, status=status.HTTP_400_BAD_REQUEST)
        serializer = UserSerializer(instance=queryset)
        return Response(data={
            'message': "用户信息获取成功",
            'results': serializer.data
        }, status=status.HTTP_200_OK)

    @transaction.atomic
    def put(self, request, pk):
        """
        更新用户信息
        :param request:
        :param pk:
        :return:
        """
        user = CustomUser.objects.filter(pk=pk).first()
        if not user:
            return Response(data={'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        serializer = UserSerializer(instance=user, data=request.data, partial=True)
        # 检查修改参数中是否带有密码
        if 'password' in request.data:
            return Response({'error': '不允许在此接口修改密码'}, status=status.HTTP_400_BAD_REQUEST)
        if serializer.is_valid():
            serializer.save()
            return Response(data={
                'results': serializer.data,
                'message': "用户信息更新成功"
            }, status=status.HTTP_200_OK)
        errors = {field: error[0] for field, error in serializer.errors.items()}
        return Response({
            'error': errors,
        }, status=status.HTTP_400_BAD_REQUEST)


class PasswordChangeView(APIView):
    # permission_classes = [IsAuthenticated]

    def put(self, request, pk):
        """
        更新用户密码
        :param request:
        :param pk:
        :return: 返回更新结果
        """
        user = CustomUser.objects.get(pk=pk)
        current_password = request.data.get('current_password')
        new_password = request.data.get('new_password')
        confirm_password = request.data.get('confirm_password')

        if not current_password or not new_password or not confirm_password:
            return Response({'error': "请输入密码"}, status=status.HTTP_400_BAD_REQUEST)

        if new_password != confirm_password:
            return Response({'error': "两次输入的密码不一致"}, status=status.HTTP_400_BAD_REQUEST)

        # 校验原密码是否正确
        if not user.check_password(current_password):
            return Response({'error': "当前密码不正确"}, status=status.HTTP_400_BAD_REQUEST)

        # 确保新密码与当前密码不同
        if current_password == new_password:
            return Response({'error': "新密码与当前密码相同"}, status=status.HTTP_400_BAD_REQUEST)

        # 加密新密码并更新用户密码
        user.password = make_password(new_password)
        user.save()

        return Response({'message': '密码更新成功'}, status=status.HTTP_200_OK)
